import 'dart:math';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

class WordService {
  static List<String> _words = [];
  static bool _isInitialized = false;

  static Future<void> initialize() async {
    if (_isInitialized) return;

    try {
      final String content = await rootBundle.loadString('assets/CET4_edited.txt');
      final List<String> lines = content.split('\n');
      
      // 解析单词
      for (String line in lines) {
        // 跳过空行和标题行
        if (line.trim().isEmpty || !line.contains('[')) continue;
        
        // 提取单词（取第一个空格前的部分）
        String word = line.split(' ')[0].trim().toLowerCase();
        if (word.isNotEmpty) {
          _words.add(word);
        }
      }
      
      _isInitialized = true;
    } catch (e) {
      if (kDebugMode) {
        print('Error loading words: $e');
      }
      // 如果加载失败，添加一些默认单词
      _words = ['hello', 'world', 'good', 'morning', 'flutter'];
    }
  }

  static String getRandomWords(int count) {
    if (_words.isEmpty) return 'hello world';
    
    final List<String> selectedWords = [];
    final random = Random();
    
    for (int i = 0; i < count; i++) {
      selectedWords.add(_words[random.nextInt(_words.length)]);
    }
    
    return selectedWords.join(' ');
  }
}